package com.spring.study.autowire_reflection;

import com.my.spring.source.simple_reflection.UserController;
import com.my.spring.source.simple_reflection.ZlxAutowire;
import org.junit.Test;

import java.lang.annotation.Annotation;
import java.util.Arrays;
import java.util.stream.Stream;

/**
 * @author zlx
 * @Description 模拟@Autowire操作
 * @Date 2020-07-15
 * @Param
 * @return
 **/
public class MyTest2 {

    @Test
    public void testAutowire(){

        for(int i=0;i < 10;i++){
            try{
                System.out.println("i======" + i);
                int a= 10/0;
            }catch (Exception e){
                e.printStackTrace();
            }
        }

        System.out.println("------------------------------------------");
        try{
            for(int i=0;i < 10;i++){
                    System.out.println("i======" + i);
                    int a= 10/0;
            }
        }catch (Exception e){
            e.printStackTrace();
        }


        UserController userController = new UserController();
//不需要新建
//        UserService userService = new UserService();

        Class clazz = userController.getClass();

        //获取类的注解
        Annotation[] annotations = clazz.getAnnotations();
        System.out.println("-=------" + annotations.length);
        for(Annotation annotation : annotations){
            System.out.println(annotation.toString());
        }

        Stream.of(clazz.getDeclaredFields()).forEach(field -> {

            Annotation annotation = field.getAnnotation(ZlxAutowire.class);
            field.setAccessible(true);
            if(annotation != null){
                //获取属性类型
                Class<?> fieldType = field.getType();
                try {
                    //用newInstance 方法创建UserService类
                    Object o = fieldType.newInstance();
                    //为userController设置属性
                    field.set(userController, o);
                }catch (InstantiationException e){
                    e.printStackTrace();
                }catch (IllegalAccessException e){
                    e.printStackTrace();
                }

            }
        });

        System.out.println(userController.getUserService());
    }
}
